package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ejlchina.searcher.BeanSearcher;
import com.ejlchina.searcher.operator.Equal;
import com.ejlchina.searcher.util.MapUtils;
import com.sky.constant.MessageConstant;
import com.sky.constant.WxConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.ServiceException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.DateUtils;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.StringUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @Author tzl
 * @Date 2023-07-14 20:42:55  星期五
 * @Description: 微信用户业务实现类
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private BeanSearcher beanSearcher;

    @Autowired
    private WeChatProperties weChatProperties;

    /**
     * 微信用户登陆
     * @param dto 微信用户登陆信息
     * @return
     */
    @Override
    public User wxLogin(UserLoginDTO dto) {
        String openid = getOpenid(dto.getCode());
        //判断用户的openid是否获取成功，不成功抛出异常
        if (StringUtils.isEmpty(openid)) {
            throw new ServiceException(MessageConstant.LOGIN_FAILED);
        }
        //获取到用户的openid是否在系统的存在
        Map<String, Object> build = MapUtils.builder()
                .field(User::getOpenid,openid).op(Equal.class)
                .build();
        User user = beanSearcher.searchFirst(User.class, build);
        if(Objects.isNull(user)){
            user = new User();
            user.setOpenid(openid);
            String name = RandomStringUtils.randomAlphanumeric(8);
            user.setName("微信用户"+name);
            user.setCreateBy(user.getName());
            user.setCreateTime(DateUtils.getNowDate());
            user.setUpdateBy(user.getName());
            user.setUpdateTime(DateUtils.getNowDate());
            userMapper.insert(user);
        }
        return user;
    }

    /**
     * 调用微信登录接口，返回微信用户的openid
     * @param code 微信登录code参数
     * @return
     */
    private String getOpenid(String code) {
        Map<String, String> params = new HashMap<>();
        params.put("appid", weChatProperties.getAppid());
        params.put("secret", weChatProperties.getSecret());
        params.put("js_code", code);
        params.put("grant_type", "authorization_code");
        //获取微信登录返回json数据
        String json = HttpClientUtil.doGet(WxConstant.WX_LOGIN_URL, params);

        //获取微信用户的openid
        JSONObject jsonObject = JSON.parseObject(json);
        String openid = jsonObject.getString("openid");
        return openid;
    }

}
